#pragma once
#include "Market.hpp"

#include <thread>
#include <atomic>
#include <string>
#include <fstream>

class TradingPlatform
{
private:
    std::vector<std::weak_ptr<StockMarket::ETF>> m_etfs;
    std::map<int, std::vector<long long>> m_price_history;
    std::atomic<bool> m_running{true};

public:
    TradingPlatform() {}
    ~TradingPlatform() {}
    inline void addETF(std::weak_ptr<StockMarket::ETF> etf)
    {
        m_etfs.push_back(etf);
    }

    void run()
    {
        while (m_running)
        {
            for (auto &etf : m_etfs)
            {
                auto ptr = etf.lock();
                if (ptr)
                {
                    long long price = ptr->getIOPV();
                    if (price != -1)
                    {
                        m_price_history[ptr->getSecurityId()].push_back(price);
                        auto stocks = ptr->getAllStockPrice();
                        for (auto &stock : stocks)
                        {
                            m_price_history[stock.first].push_back(stock.second);
                        }
                        printf("etf %d iopv: %lld\n", ptr->getSecurityId(), price);
                    }
                }
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }
    }

    inline void stop()
    {
        m_running = false;
    }

    void log(const std::string& path)
    {
        std::ofstream file(path);
        for(auto& p : m_price_history)
        {
            auto qs = m_etfs[0].lock()->getAllStockQuality();
            file << p.first << ",";
            auto q = qs.find(p.first);
            if(q != qs.end())
            {
                file << q->second << ",";
            }
            else
            {
                file << "0,";
            }
            for(auto& price : p.second)
            {
                file << price << ",";
            }
            file << std::endl;
        }
    }
};
